package com.pocket.cloud.payment.controller;

import cn.hutool.core.util.IdUtil;
import com.pocket.cloud.common.api.ResultData;
import com.pocket.cloud.common.dto.OrderSettlementDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;


/**
 * @author zhaozhile
 */
@RefreshScope
@RestController
public class PaymentController  implements ApplicationListener<RefreshScopeRefreshedEvent> {

    @Value("${pocket.enable:default}")
    private String enable;

    private static final Logger LOGGER = LoggerFactory.getLogger(PaymentController.class);

    @Scheduled(cron = "*/1 * * * * ?")
    public void printEnable(){
        LOGGER.info("获取 nacos config 配置：{}", enable);
    }


    //openfeign+sentinel进行服务降级和流量监控的整合处理case
    @GetMapping(value = "/payment/{orderNo}")
    public ResultData<OrderSettlementDTO> getPayByOrderNo(@PathVariable("orderNo") String orderNo) throws InterruptedException {
        LOGGER.info("查询 payment 服务，获取订单[{}]详情。", orderNo);
        //模拟从数据库查询出数据并赋值给DTO
        OrderSettlementDTO payDTO = new OrderSettlementDTO();

        payDTO.setSettlementId(1024L);
        payDTO.setOrderNumber(orderNo);
        payDTO.setPayAmount(BigDecimal.valueOf(9.9));
        payDTO.setPayNo("pay:"+ IdUtil.fastUUID());
        payDTO.setUserId("1");

        //TimeUnit.SECONDS.sleep(3);

        return ResultData.success(payDTO);
    }

    /**
     * 解决 @RefreshScope 导致注解 @Scheduled 失效问题
     * <a href="https://blog.csdn.net/weixin_48568302/article/details/139170322">...</a>
     * @param event
     */
    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {

    }

//    public ResultData handlerBlockHandler(@PathVariable("orderNo") String orderNo, BlockException exception)
//    {
//        return ResultData.fail(ReturnCodeEnum.RC500.getCode(),"getPayByOrderNo服务不可用，" +
//                "触发sentinel流控配置规则"+"\t"+"o(╥﹏╥)o");
//    }

    /*
    fallback服务降级方法纳入到Feign接口统一处理，全局一个
    public ResultData myFallBack(@PathVariable("orderNo") String orderNo,Throwable throwable)
    {
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(),"异常情况："+throwable.getMessage());
    }*/


}
